package com.hst.web.base.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.hst.core.ServiceContext;
import com.hst.core.dao.IORDao;
import com.hst.core.dao.ISQLDao;
import com.hst.core.json.JsonUtil;
import com.hst.web.auth.po.User;
import com.hst.web.base.service.UserRoleService;
import com.hst.web.common.utils.ConstantUtil;

@Controller
@RequestMapping("/dept")
public class DeptController {

	@Autowired
	ISQLDao sql;

	@Autowired
	IORDao dao;

	private String importTemplate = "./template/contractor_emp.xlsx";

	@SuppressWarnings("unchecked")
	@RequestMapping("/company-dept")
	public void info(@RequestBody(required = false) String data, Model m)
			throws JsonParseException, JsonMappingException, IOException {
		Map<String, Object> params = null;
		if (data != null)
			params = JsonUtil.read(data, Map.class);
		else {
			params = new HashMap<String, Object>();
			User u = (User) ServiceContext.getInstance().getUser();
			if (u.getPrivileges().contains(ConstantUtil.COMPANY_MANAGER_PRIVLIGE))
				UserRoleService.addCompanyParam(params);
			else
				UserRoleService.addDeptParam(params);
		}

		m.addAttribute("company-dept", sql.query("dept.dept-info", params));

	}

	@RequestMapping("/download-template")
	public void downloadTempate(HttpServletResponse res) throws IOException {
		File file = new File(importTemplate);
		try (InputStream bis = new BufferedInputStream(new FileInputStream(file))) {
			try (BufferedOutputStream bos = new BufferedOutputStream(res.getOutputStream())) {
				IOUtils.copy(bis, bos);
			}
		}
	}

}
